package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.PaymentUserDao;
import com.xbongbong.saas.domain.entity.PaymentUserEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.enums.subform.PaymentSheetTeamEnum;
import com.xbongbong.saas.enums.subform.PaymentTeamEnum;
import com.xbongbong.saas.model.PaymentUserModel;
import com.xbongbong.sys.domain.entity.UserEntity;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author haibin.zhang
 * @version v1.0
 * @date 2019/4/11 15:13
 * @since v1.0
 */
@Component
@Service("paymentUserModel")
public class PaymentUserModelImpl implements PaymentUserModel {
    @Resource
    private PaymentUserDao paymentUserDao;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;

    @Override
    public Integer insert(PaymentUserEntity entity) throws XbbException {
        paymentUserDao.insert(entity);
        PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferUserTeamToFormData(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM, entity);
        InsertDTO saveDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM);
//        InsertDTO insertDTO = new InsertDTO();
//        insertDTO.setWaitUntil(WriteRequest.RefreshPolicy.NONE);
//        insertDTO.setEsId(entity.getCorpid() + "_" + entity.getId());
//        insertDTO.setParent(entity.getCorpid() + "_" + entity.getDataId());
//        insertDTO.setSource(BeanUtil.convertBean2Map(entity, false, true));
//        insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM);
        paasEsModel.insert(saveDTO);
        return null;
    }

    @Override
    public Integer update(PaymentUserEntity entity) throws XbbException {
        long now = DateTimeUtil.getInt();
        entity.setUpdateTime(now);
        Integer result = paymentUserDao.update(entity);

        PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferUserTeamToFormData(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM, entity);
        InsertDTO saveDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM);
        paasEsModel.update(saveDTO);
//        paasEsModel.update(entity,IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM,entity.getCorpid(),entity.getId(),entity.getDataId());
        return result;
    }

    @Override
    public List<PaymentUserEntity> findEntitys(Map<String, Object> param) {
        return paymentUserDao.findEntitys(param);
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return paymentUserDao.getEntitysCount(param);
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return paymentUserDao.findEntitys(param);
    }

    @Override
    public Integer save(PaymentUserEntity paymentUserEntity) throws XbbException {
        if (paymentUserEntity.getId() == null || paymentUserEntity.getId() == 0L) {
            return insert(paymentUserEntity);
        }  else {
            return update(paymentUserEntity);
        }
    }

    @Override
    public PaymentUserEntity getByKey(Long key, String corpid) {
        return paymentUserDao.getByKey(key, corpid);
    }

    @Override
    public List<PaymentUserEntity> findAllEntitys(Map<String, Object> param) {
        return paymentUserDao.findEntitys(param);
    }

    @Override
    public List<String> getContractUserIdList(String corpid, Long contractId, Integer isMain) {
        return null;
    }

    @Override
    public List<String> getContractUserIdList(String corpid, List<String> contractIds, Integer isMain) {
        return null;
    }

    @Override
    public void disbandedTeamByCustomerId(String corpid, List<Long> customerIdList) throws XbbException {
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("customerIdIn",customerIdList);
        map.put("del",DelEnum.NORMAL.getDel());
        List<PaymentUserEntity> paymentUserEntityList = findEntitys(map);
        paymentUserDao.disbandedTeamByCustomerId(corpid,customerIdList);
        for (PaymentUserEntity entity : paymentUserEntityList){
            paasEsModel.delete(entity.getId(), corpid, IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM,entity.getDataId());
        }

    }

    @Override
    public void disbandedTeamByDataId(String corpid, List<Long> dataIdList) throws XbbException {
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put(ParameterConstant.CORPID, corpid);
        map.put(ParameterConstant.DATA_ID_IN, dataIdList);
        map.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaymentUserEntity> paymentUserEntityList = findEntitys(map);
        paymentUserDao.disbandedTeamByDataId(corpid,dataIdList);
        for (PaymentUserEntity entity : paymentUserEntityList){
            paasEsModel.delete(entity.getId(), corpid, IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM,entity.getDataId());
        }

    }

    @Override
    public void delete(PaymentUserEntity paymentUserEntity) throws XbbException {
        paymentUserEntity.setDel(1);
        paymentUserEntity.setUpdateTime((long) DateUtil.getInt());
        paymentUserDao.update(paymentUserEntity);
        paasEsModel.delete(paymentUserEntity.getId(), paymentUserEntity.getCorpid(), IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM, paymentUserEntity.getDataId());
//        paasEsModel.update(paymentUserEntity,IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM,paymentUserEntity.getCorpid(),paymentUserEntity.getId(),paymentUserEntity.getDataId());
    }

    @Override
    public void contractUserInsert(UserEntity userEntity, Long contractId, Integer isMain) throws XbbException {

    }

    @Override
    public List<UserTeamEntity> findBaseEntitys(Map<String, Object> map) {
        return paymentUserDao.findBaseEntitys(map);
    }

    @Override
    public Integer deleteByContractIdIn(List<Long> contractIdIn, String corpid) throws XbbException {
        return null;
    }

    @Override
    public List<Long> getDataIdList(String corpid, Integer isMain, List<String> userId) {
        return null;
    }

    @Override
    public void insertBatch(List<PaymentUserEntity> paymentUserEntityList) throws XbbException{
        insertBatch(paymentUserEntityList, WriteRequest.RefreshPolicy.NONE);
    }

    @Override
    public void insertBatch(List<PaymentUserEntity> paymentUserEntityList, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException{
        paymentUserDao.insertBatch(paymentUserEntityList);
        List<PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferUserTeamToFormDataList(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM, paymentUserEntityList);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
            insertDTOList.add(paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM));
        }
        paasEsModel.insertBatch(insertDTOList, refreshPolicy);
    }



    @Override
    public void batchUpdateByUserIdIn(String corpid, List<Long> dataIdIn, List<UserTeamEntity> teamEntityList, Integer isMain, Integer del) throws XbbException {
        batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, del, WriteRequest.RefreshPolicy.WAIT_UNTIL);
    }

    @Override
    public void batchUpdateByUserIdIn(String corpid, List<Long> dataIdIn, List<UserTeamEntity> teamEntityList, Integer isMain, Integer del, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        paymentUserDao.batchUpdateByIdIn(corpid, dataIdIn, isMain, del);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                JSONObject object = new JSONObject();
                object.put(PaymentTeamEnum.IS_MAIN.getDataAttr(), isMain);
                map.put(StringConstant.JSON_DATA, object);
            }
            if (Objects.nonNull(del)) {
                map.put(ParameterConstant.DEL, del);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy);
    }

    @Override
    public void batchDelete(String corpid, List<PaymentUserEntity> removeList) throws XbbException {
        List<Long> removeIdList = new ArrayList<>();
        removeList.forEach(entity -> removeIdList.add(entity.getId()));
        paymentUserDao.batchDeleteById(corpid, removeIdList);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaymentUserEntity entity : removeList){
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM);
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM.getIndex());
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM.getType());
            Map<String,Object> sourceMap = new HashMap<>();
            sourceMap.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
            sourceMap.put(StringConstant.DEL,DelEnum.DELETE.getDel());
            insertDTO.setSource(sourceMap);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertDTOList);
    }

    @Override
    public void updateBatchCustomerId(List<PaymentUserEntity> paymentUserEntityList, String corpid) throws XbbException {
        paymentUserDao.updateBatchCustomerId(paymentUserEntityList,corpid);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaymentUserEntity entity : paymentUserEntityList){
            Map<String,Object> map = new HashMap<>();
            JSONObject object = new JSONObject();
            object.put(PaymentTeamEnum.CUSTOMER_ID.getDataAttr(),entity.getCustomerId());
            object.put(PaymentTeamEnum.CONTRACT_ID.getDataAttr(),entity.getContractId());
            map.put(StringConstant.JSON_DATA, object);
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM);
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM.getIndex());
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM.getType());
            insertDTO.setSource(map);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertDTOList);
    }

    @Override
    public void deleteBatchUser(List<PaymentUserEntity> paymentUserEntityList, String corpid) throws XbbException {
        List<Long> idList = new ArrayList<>();
        List<InsertDTO> insertDTOList = new ArrayList<>();
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put(StringConstant.DEL, DelEnum.DELETE.getDel());
        map.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
        for (PaymentUserEntity entity : paymentUserEntityList){
            idList.add(entity.getId());
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM);
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM.getIndex());
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM.getType());
            insertDTO.setSource(map);
            insertDTOList.add(insertDTO);
        }
        deleteBatch(idList,corpid);
        paasEsModel.updateBatch(insertDTOList);
    }

    /**
     * 编辑协同人表单权限
     *
     * @param paymentUserEntity
     * @throws XbbException
     */
    @Override
    public void updateEditFormPer(PaymentUserEntity paymentUserEntity) throws XbbException {
        updateFormTeam(paymentUserEntity);
    }

    /**
     * 编辑标签
     *
     * @param paymentUserEntity
     */
    @Override
    public void editLabel(PaymentUserEntity paymentUserEntity) throws XbbException{
        updateFormTeam(paymentUserEntity);
    }

    private void updateFormTeam(PaymentUserEntity paymentUserEntity) throws XbbException {
        Long updateTime = DateTimeUtil.getInt();
        paymentUserEntity.setUpdateTime(updateTime);
        paymentUserDao.update(paymentUserEntity);
        InsertDTO insertDTO = new InsertDTO();
        String corpid = paymentUserEntity.getCorpid();
        insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM.getType() + "_" + corpid + "_" + paymentUserEntity.getId());
        insertDTO.setParent(corpid + "_" + paymentUserEntity.getDataId());
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("updateTime", updateTime);
        insertDTO.setSource(map);
        insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM);
        paasEsModel.update(insertDTO);
    }

    private void deleteBatch(List<Long> idList, String corpid) {
        paymentUserDao.deleteBatch(idList, corpid);
    }

    /**
     * 批量更新团队的人员为协同人身份以及协同人的可编辑权限
     *
     * @param corpid
     * @param dataIdIn
     * @param teamEntityList
     * @param isMain
     * @param needThrow
     * @throws XbbException
     */
    @Override
    public void batchUpdateCoAndPerByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> teamEntityList, Integer isMain, boolean needThrow) throws XbbException {
        batchUpdateCoAndPerByUserIdIn(corpid, idIn, teamEntityList, isMain, needThrow, WriteRequest.RefreshPolicy.WAIT_UNTIL);
    }


    @Override
    public void batchUpdateCoAndPerByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> teamEntityList, Integer isMain, boolean needThrow, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        Integer formPermission = teamEntityList.get(BasicConstant.ZERO).getFormPermission();
        paymentUserDao.batchUpdateCoAndPerByUserIdIn(corpid, idIn, isMain, formPermission);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                JSONObject object = new JSONObject();
                object.put(PaymentSheetTeamEnum.IS_MAIN.getDataAttr(), isMain);
                map.put(StringConstant.JSON_DATA, object);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy, needThrow);
    }


}
